import axios from "axios";
import { getToken } from "./auth";
import { Message, Modal } from "@arco-design/web-vue";
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
});

let isAuthError = ref(false);
// request拦截器
service.interceptors.request.use(config => {

  const token = getToken();
  config.headers.Authorization = `${token}`;
  config.headers.token = `${token}`;
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;
    return res;
    // if the custom code is not 1, it is judged as an error.
    if (res.code !== 1) {
      // 4001: Other clients logged in; 4002: Token expired; 4003: Illegal token;
      if ([4001, 4002, 4003].includes(res.code)) {
        if (!isAuthError.value) {
          isAuthError.value = true;
          Modal.error({
            title: "鉴权失败",
            content: "您已注销，点击右上角头像切换用户重新登录。",
            onClose: () => (isAuthError.value = false),
          });
        }
      } else {
        Message.error({
          content: res.msg || "请求出错",
          duration: 5 * 1000,
        });
      }

      return Promise.reject(new Error(res.msg || "请求出错"));
    } else {
      return res;
    }
  },
  (error) => {

    Message.error({
      content: error.response.data.message || "请求出错",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}


export default service;
